<template>
  <div class="warehousings-container">
    <!-- Search Bar -->
    <el-card class="search-card" shadow="never">
      <el-form :inline="true" :model="searchForm" class="search-form" label-width="80px">
        <el-form-item label="入库编码">
          <el-input
            v-model="searchForm.warehousingCode"
            placeholder="请输入入库编码"
            clearable
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="入库名称">
          <el-input
            v-model="searchForm.warehousingName"
            placeholder="请输入入库名称"
            clearable
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="入库时间">
          <el-date-picker
            v-model="searchForm.warehousingTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 260px"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- Table -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">采购入库列表</span>
          <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        size="small"
        stripe
        border
        style="width: 100%"
        @row-click="handleRowClick"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="warehousingCode" label="入库编码" width="160" sortable align="center" show-overflow-tooltip />
        <el-table-column prop="warehousingName" label="入库名称" width="180" align="center" show-overflow-tooltip />
        <el-table-column prop="warehousingTime" label="入库时间" width="180" sortable align="center" show-overflow-tooltip />
        <el-table-column prop="supplierId" label="客户" width="160" align="center">
          <template #default="scope">
            <span>{{ getCustomerName(scope.row.supplierId) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.state === 1">已入库</el-tag>
            <el-tag type="info" v-else-if="scope.row.state === 2">已出库</el-tag>
            <span v-else>{{ scope.row.state }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="noTe" label="备注" min-width="160" show-overflow-tooltip />
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              :icon="Edit"
              @click.stop="handleEdit(scope.row)"
              link
            >
              编辑
            </el-button>
            <el-button
              size="small"
              link
              @click.stop="openProductDialog(scope.row)"
            >
              产品管理
            </el-button>
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click.stop="handleDelete(scope.row)"
              link
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- Add/Edit Dialog -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="入库编码" prop="warehousingCode">
          <el-input
            v-model="formData.warehousingCode"
            placeholder="请输入入库编码"
            clearable
          />
        </el-form-item>
        <el-form-item label="入库名称" prop="warehousingName">
          <el-input
            v-model="formData.warehousingName"
            placeholder="请输入入库名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="入库时间" prop="warehousingTime">
          <el-date-picker
            v-model="formData.warehousingTime"
            type="datetime"
            placeholder="选择入库时间"
            style="width: 100%"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="供应商ID" prop="supplierId">
          <el-select v-model="formData.supplierId" filterable placeholder="请选择客户" style="width: 100%">
            <el-option
              v-for="item in customerOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="noTe">
          <el-input
            v-model="formData.noTe"
            type="textarea"
            :rows="4"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="formData.state" placeholder="请选择状态" style="width: 100%">
            <el-option :value="1" label="已入库" />
            <el-option :value="2" label="已出库" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  <!-- Product Manage Dialog -->
  <el-dialog
    v-model="productDialog.visible"
    title="产品管理"
    width="70%"
    align-center
    :close-on-click-modal="false"
  >
    <div class="product-toolbar" style="display:flex;justify-content:space-between;align-items:center;">
      <div>
        <el-button type="primary" size="small" :icon="Plus" @click="openProductSelect">新增</el-button>
      </div>
      <div style="display:flex;gap:8px;">
        <el-button size="small" @click="selectAllInDialog">全选</el-button>
        <el-button size="small" @click="invertSelectInDialog">反选</el-button>
      </div>
    </div>
    <el-table
      ref="productDialogTableRef"
      :data="productDialog.items"
      border
      size="small"
      style="width: 100%"
      @selection-change="onDialogSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column type="index" label="#" width="60" align="center" />
      <el-table-column prop="productCode" label="产品编号" width="180" show-overflow-tooltip />
      <el-table-column prop="productName" label="产品名称" width="180" show-overflow-tooltip />
      <el-table-column prop="spec" label="规格型号" width="200" show-overflow-tooltip />
      <el-table-column prop="state" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag size="small" type="success" v-if="scope.row.state === 1">已入库</el-tag>
          <el-tag size="small" type="info" v-else-if="scope.row.state === 2">已出库</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="单位" width="80" align="center">
        <template #default>件</template>
      </el-table-column>
      <el-table-column label="接收数量" width="140" align="center">
        <template #default="scope">
          <el-input v-model="scope.row.qty" size="small" placeholder="请输入" style="width: 110px" />
        </template>
      </el-table-column>
      <el-table-column label="批次号" width="180">
        <template #default="scope">
          <el-input v-model="scope.row.batchNo" size="small" placeholder="请输入批次号" />
        </template>
      </el-table-column>
      <el-table-column label="仓库" width="160">
        <template #default="scope">
          <el-select v-model="scope.row.warehouse" size="small" placeholder="选择仓库" style="width: 140px" @change="onWarehouseChange(scope.row)">
            <el-option v-for="w in productDialog.warehouses" :key="w.value" :label="w.label" :value="w.value" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="库区" width="140">
        <template #default="scope">
          <el-select v-model="scope.row.area" size="small" placeholder="选择库区" style="width: 120px" @change="onAreaChange(scope.row)">
            <el-option v-for="a in getAreaOptions(scope.row.warehouse)" :key="a.value" :label="a.label" :value="a.value" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="库位" width="140">
        <template #default="scope">
          <el-select v-model="scope.row.location" size="small" placeholder="选择库位" style="width: 120px">
            <el-option v-for="l in getLocationOptions(scope.row.warehouse, scope.row.area)" :key="l.value" :label="l.label" :value="l.value" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="140" align="center">
        <template #default>
          <el-link type="primary" :underline="false">编辑</el-link>
          <span style="margin: 0 8px; color: #c0c4cc">|</span>
          <el-link type="danger" :underline="false">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="productDialog.visible=false">返回</el-button>
        <el-button type="warning" @click="submitProductModels('out')">出库</el-button>
        <el-button type="primary" @click="submitProductModels('in')">入库</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- Product Select Dialog -->
  <el-dialog
    v-model="productSelect.visible"
    title="选择产品"
    width="70%"
    align-center
    :close-on-click-modal="false"
  >
    <!-- Search Bar -->
    <el-form :inline="true" :model="productSelect.form" class="search-form" label-width="80px" style="margin-bottom:12px;">
      <el-form-item label="产品编号">
        <el-input v-model="productSelect.form.productNumber" placeholder="产品编号" clearable style="width:220px" />
      </el-form-item>
      <el-form-item label="产品名称">
        <el-input v-model="productSelect.form.productName" placeholder="产品名称" clearable style="width:220px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="loadProductList(true)">查询</el-button>
        <el-button size="small" @click="resetProductSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="product-toolbar" style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
      <div>
        <el-button size="small" @click="selectAllProducts">全选本页</el-button>
        <el-button size="small" @click="invertSelectProducts">反选本页</el-button>
        <el-button size="small" @click="clearSelectProducts">清空选择</el-button>
      </div>
      <div>已选择 {{ productSelect.selectedIds.size }} 条</div>
    </div>

    <el-table
      ref="productSelectTableRef"
      :data="productSelect.list"
      border
      size="small"
      style="width: 100%"
      :row-key="row => row.id"
      @selection-change="onProductSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" reserve-selection />
      <el-table-column type="index" label="#" width="60" align="center" />
      <el-table-column prop="productNumber" label="产品编号" width="150" show-overflow-tooltip />
      <el-table-column prop="productName" label="产品名称" width="160" show-overflow-tooltip />
      <el-table-column prop="productModel" label="规格型号" width="160" show-overflow-tooltip />
      <el-table-column prop="productSpecification" label="规格" width="120" show-overflow-tooltip />
      <el-table-column prop="productQuantity" label="库存" width="100" align="center" />
      <el-table-column label="图片" width="90" align="center">
        <template #default="scope">
          <img :src="getImgUrl(scope.row.productImage)" alt="" style="width:56px;height:40px;object-fit:cover;border-radius:4px;" />
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="productSelect.page"
        v-model:page-size="productSelect.size"
        :total="productSelect.total"
        :page-sizes="[10,20,50,100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="(s)=>{productSelect.size=s;loadProductList()}"
        @current-change="(p)=>{productSelect.page=p;loadProductList()}"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="productSelect.visible=false">取消</el-button>
        <el-button type="primary" @click="confirmSelectProducts">确定</el-button>
      </span>
    </template>
  </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete } from '@element-plus/icons-vue'
import http from '@/api/http'

// Search form
const searchForm = reactive({
  warehousingCode: '',
  warehousingName: '',
  warehousingTime: []
})

// Table data
const tableData = ref([])
const loading = ref(false)

// Pagination
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// Dialog
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const formRef = ref(null)
const isEdit = ref(false)
// 自动编码序列缓存
const pendingSeq = ref(null)
const currentYearMonth = ref('')

// Form data
const formData = reactive({
  id: null,
  warehousingCode: '',
  warehousingName: '',
  warehousingTime: '',
  supplierId: null,
  noTe: '',
  state: 1,
  productCode: ''
})

// Customer options
const customerOptions = ref([])
const getCustomerName = (id) => {
  const opt = customerOptions.value.find(x => x.value === id)
  return opt ? opt.label : id
}

// 产品管理弹窗数据
const productDialog = reactive({
  visible: false,
  items: [],
  headerId: null,
  warehouses: [], // [{value,label}]
  areasRaw: [],   // 原始数据, 含cId
  locationsRaw: [], // 原始数据, 含cId/kId
  selectedItems: []
})
const openProductDialog = async (row) => {
  productDialog.visible = true
  productDialog.headerId = row.id
  // 数据来源由后端接口提供，此处不生成模拟数据
  productDialog.items = []
  // 加载仓库/库区/库位下拉数据
  try {
    const [wRes, aRes, lRes] = await Promise.all([
      http.get('api/WarehouseQuery/GetAllWarehouseModelling'),
      http.get('api/WarehouseQuery/GetAllReservoirareaModelling'),
      http.get('api/WarehouseQuery/GetAllStorageLocationModelling')
    ])
    if (wRes && wRes.success) {
      productDialog.warehouses = (wRes.data || []).map(x => ({ value: x.id, label: x.warehouseName }))
    }
    if (aRes && aRes.success) {
      productDialog.areasRaw = aRes.data || []
    }
    if (lRes && lRes.success) {
      productDialog.locationsRaw = lRes.data || []
    }
    // 反填：根据主表的 productCode 调后端批量填充明细
    const codeStr = row.productCode || ''
    const codes = codeStr
      ? codeStr.split(/[,，\s]+/).map(s => s.trim()).filter(s => s)
      : []
    if (codes.length > 0) {
      const fillRes = await http.post('api/WMS/BatchFillProductModelsByCode', codes, false)
      if (fillRes && (fillRes.success || fillRes.status)) {
        const list = Array.isArray(fillRes.data) ? fillRes.data : []
        productDialog.items = list.map(x => ({
          id: x.id || x.productId || 0,
          productCode: x.productCode || x.productNumber || '',
          productName: x.productName || '',
          spec: x.productGui || x.productModel || x.productSpecification || '',
          qty: x.productNum || x.qty || '',
          batchNo: x.productCores || x.batchNo || '',
          warehouse: x.warehouseId || null,
          area: x.reservoirId || null,
          location: x.storageId || null,
          state: (x.state ?? x.productStatus ?? x.status ?? null)
        }))
      }
    }
  } catch (e) { console.log(e) }
}

// 选择产品弹窗状态
const productSelect = reactive({
  visible: false,
  form: { productNumber: '', productName: '' },
  page: 1,
  size: 10,
  total: 0,
  list: [],
  selectedIds: new Set()
})
const productSelectTableRef = ref(null)
const productDialogTableRef = ref(null)
const openProductSelect = () => {
  productSelect.visible = true
  productSelect.page = 1
  loadProductList(true)
}
const resetProductSearch = () => {
  productSelect.form.productNumber = ''
  productSelect.form.productName = ''
  productSelect.page = 1
  loadProductList(true)
}
const loadProductList = async (resetSelection=false) => {
  const res = await http.get('api/WMS/GetProductInformationPage', {
    pageIndex: productSelect.page,
    pageSize: productSelect.size,
    productNumber: productSelect.form.productNumber || '',
    productName: productSelect.form.productName || ''
  })
  if (res && res.success) {
    productSelect.list = res.data || []
    productSelect.total = res.total || 0
    if (resetSelection && productSelectTableRef.value) {
      productSelectTableRef.value.clearSelection()
      productSelect.selectedIds.clear()
    }
  }
}
const getRowId = (row) => row.id
const selectAllProducts = () => {
  if (!productSelectTableRef.value) return
  productSelect.list.forEach(row => {
    productSelectTableRef.value.toggleRowSelection(row, true)
    productSelect.selectedIds.add(getRowId(row))
  })
}
const invertSelectProducts = () => {
  if (!productSelectTableRef.value) return
  productSelect.list.forEach(row => {
    const rid = getRowId(row)
    const selected = productSelect.selectedIds.has(rid)
    productSelectTableRef.value.toggleRowSelection(row, !selected)
    if (selected) productSelect.selectedIds.delete(rid); else productSelect.selectedIds.add(rid)
  })
}
const clearSelectProducts = () => {
  if (!productSelectTableRef.value) return
  productSelectTableRef.value.clearSelection()
  productSelect.selectedIds.clear()
}
const onProductSelectionChange = (rows) => {
  const ids = new Set(rows.map(r => getRowId(r)))
  productSelect.selectedIds = ids
}

// 确认选择：把选择的产品行添加到产品管理表格
const confirmSelectProducts = () => {
  const selectedRows = productSelect.list.filter(x => productSelect.selectedIds.has(getRowId(x)))
  selectedRows.forEach(x => {
    productDialog.items.push({
      id: x.id,
      productCode: x.productNumber,
      productName: x.productName,
      spec: x.productModel || x.productSpecification || '',
      qty: '',
      batchNo: '',
      warehouse: null,
      area: null,
      location: null,
      state: null
    })
  })
  productSelect.visible = false
}

// 图片地址拼接
function getImgUrl(p) {
  if (!p) return ''
  return p.startsWith('http') ? p : ((window.ipAddress || '') + p.replace(/^\/?/, ''))
}

// 联动与选项构造
const onWarehouseChange = (row) => {
  row.area = null
  row.location = null
}
const onAreaChange = (row) => {
  row.location = null
}
const getAreaOptions = (warehouseId) => {
  if (!warehouseId) return []
  return (productDialog.areasRaw || [])
    .filter(a => a.cId === warehouseId)
    .map(a => ({ value: a.id, label: a.reservoirareaName }))
}
const getLocationOptions = (warehouseId, areaId) => {
  if (!warehouseId || !areaId) return []
  return (productDialog.locationsRaw || [])
    .filter(l => l.cId === warehouseId)
    .map(l => ({ value: l.id, label: l.storagelocationName }))
}

// 对话框选择变化
const onDialogSelectionChange = (rows) => {
  productDialog.selectedItems = rows || []
}
// 全选/反选
const selectAllInDialog = () => {
  if (!productDialogTableRef.value) return
  productDialogTableRef.value.clearSelection()
  ;(productDialog.items || []).forEach(r => productDialogTableRef.value.toggleRowSelection(r, true))
}
const invertSelectInDialog = () => {
  if (!productDialogTableRef.value) return
  const selected = new Set((productDialog.selectedItems || []).map(r => r))
  ;(productDialog.items || []).forEach(r => {
    const isSel = selected.has(r)
    productDialogTableRef.value.toggleRowSelection(r, !isSel)
  })
}

// 提交产品明细（入库/出库）
const submitProductModels = async (direction = 'in') => {
  if (!productDialog.headerId) {
    ElMessage.error('未获取到主表Id')
    return
  }
  try {
    if (direction === 'out') {
      // 出库：必须选中数据，发送所选行主键ID数组
      const sel = (productDialog.selectedItems && productDialog.selectedItems.length > 0)
        ? productDialog.selectedItems
        : []
      if (sel.length === 0) {
        ElMessage.warning('请先选择需要出库的行')
        return
      }
      const ids = Array.from(new Set(sel
        .map(x => (x.id ?? x.productId))
        .filter(v => v !== undefined && v !== null && v !== 0)))
        .map(v => v.toString())
      if (ids.length === 0) {
        ElMessage.error('选中行缺少主键Id')
        return
      }
      const url = `api/WMS/BatchUpdateProductStateToOut?warehousingId=${encodeURIComponent(productDialog.headerId)}`
      const res = await http.post(url, ids, '提交中...')
      if (res && (res.success || res.status)) {
        ElMessage({ type: 'success', message: '出库成功', showClose: true })
        productDialog.visible = false
      } else {
        ElMessage.error((res && res.message) || '出库失败')
      }
      return
    }

    // 入库：提交选中或全部为明细
    const rowsToSubmit = (productDialog.selectedItems && productDialog.selectedItems.length > 0)
      ? productDialog.selectedItems
      : productDialog.items
    const payload = rowsToSubmit.map(x => ({
      productId: 0,
      productCode: x.productCode || '',
      productName: x.productName || '',
      productGui: x.spec || '',
      productdan: '件',
      productNum: Number(x.qty || 0),
      productCores: x.batchNo || '',
      warehouseId: x.warehouse || 0,
      reservoirId: x.area || 0,
      storageId: x.location || 0
    }))
    const res = await http.post(`api/WMS/BatchAddProductModels?warehousingId=${productDialog.headerId}`, payload, '提交中...')
    if (res && (res.success || res.status)) {
      ElMessage({ type: 'success', message: '添加成功', showClose: true })
      productDialog.visible = false
    } else {
      ElMessage.error((res && res.message) || '添加失败')
    }
  } catch (e) {
    console.error(e)
    ElMessage.error(direction === 'out' ? '出库失败' : '添加失败')
  }
}

// Form validation rules
const formRules = {
  warehousingCode: [
    { required: true, message: '请输入入库编码', trigger: 'blur' }
  ],
  warehousingName: [
    { required: true, message: '请输入入库名称', trigger: 'blur' }
  ],
  warehousingTime: [
    { required: true, message: '请选择入库时间', trigger: 'change' }
  ]
}

// Load data
const loadData = async () => {
  loading.value = true
  try {
    // 调用后端分页接口：api/WMS/GetWarehousingsPage
    const response = await http.get('api/WMS/GetWarehousingsPage', {
      pageIndex: pagination.page,
      pageSize: pagination.size,
      warehousingCode: searchForm.warehousingCode || '',
      warehousingName: searchForm.warehousingName || '',
      startTime: (searchForm.warehousingTime && searchForm.warehousingTime[0]) ? `${searchForm.warehousingTime[0]} 00:00:00` : '',
      endTime: (searchForm.warehousingTime && searchForm.warehousingTime[1]) ? `${searchForm.warehousingTime[1]} 23:59:59` : ''
    })

    if (response && response.success) {
      tableData.value = Array.isArray(response.data) ? response.data : []
      // 如后端提供总数字段，请替换这里：pagination.total = response.total
      pagination.total = (response.total ?? pagination.total)
    } else {
      ElMessage.error((response && response.message) || '获取数据失败')
    }
  } catch (error) {
    console.error('Load data error:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// Search
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// Reset
const handleReset = () => {
  searchForm.warehousingCode = ''
  searchForm.warehousingName = ''
  searchForm.warehousingTime = []
  pagination.page = 1
  loadData()
}

// Add
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '新增采购入库'
  dialogVisible.value = true
  resetForm()
  // 自动生成入库编码：SRKYYYYMMNNN
  const ym = getYearMonth()
  const seq = getNextSeq(ym)
  pendingSeq.value = seq
  currentYearMonth.value = ym
  formData.warehousingCode = `SRK${ym}${String(seq).padStart(3, '0')}`
}

// Edit
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑采购入库'
  dialogVisible.value = true
  
  // Copy row data to form
  formData.id = row.id
  formData.warehousingCode = row.warehousingCode
  formData.warehousingName = row.warehousingName
  formData.warehousingTime = row.warehousingTime
  formData.supplierId = row.supplierId
  formData.noTe = row.noTe
  formData.state = (row.state ?? 1)
  formData.productCode = row.productCode || ''
}

// Delete
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该记录吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const payload = {
        id: row.id,
        warehousingCode: row.warehousingCode || '',
        warehousingName: row.warehousingName || '',
        warehousingTime: row.warehousingTime ? new Date(row.warehousingTime).toISOString() : '',
        supplierId: row.supplierId ?? 0,
        noTe: row.noTe || '',
        createName: row.createName || ''
      }
      const response = await http.post('api/WMS/warehousingsDelete', payload, '删除中...')
      if (response && (response.status || response.success)) {
        ElMessage.success('删除成功')
        loadData()
      } else {
        ElMessage.error((response && response.message) || '删除失败')
      }
    } catch (error) {
      console.error('Delete error:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // Cancel
  })
}

// Submit
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      const data = {
        id: isEdit.value ? formData.id : 0,
        warehousingCode: formData.warehousingCode,
        warehousingName: formData.warehousingName,
        warehousingTime: formData.warehousingTime ? new Date(formData.warehousingTime).toISOString() : '',
        supplierId: formData.supplierId,
        noTe: formData.noTe,
        createName: formData.createName || '',
        state: formData.state ?? 1,
        productCode: isEdit.value ? (formData.productCode || '') : ''
      }
      const response = isEdit.value
        ? await http.put('api/WMS/warehousingsUpdate', data, false)
        : await http.post('api/WMS/warehousingsAdd', data, false)

      if (response && (response.status || response.success)) {
        dialogVisible.value = false
        await nextTick()
        loadData()
        ElMessage({ type: 'success', message: isEdit.value ? '更新成功' : '添加成功', showClose: true })
        // 新增成功后持久化当月最新序列号
        if (!isEdit.value && pendingSeq.value != null && currentYearMonth.value) {
          localStorage.setItem(`srk_seq_${currentYearMonth.value}`, String(pendingSeq.value))
          pendingSeq.value = null
        }
      } else {
        ElMessage.error(response.message || (isEdit.value ? '更新失败' : '添加失败'))
      }
    } catch (error) {
      console.error('Submit error:', error)
      ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
    } finally {
      submitLoading.value = false
    }
  })
}

// Dialog close
const handleDialogClose = () => {
  formRef.value?.clearValidate()
  resetForm()
}

// Reset form
const resetForm = () => {
  formData.id = null
  formData.warehousingCode = ''
  formData.warehousingName = ''
  formData.warehousingTime = ''
  formData.supplierId = null
  formData.noTe = ''
}

// Row click
const handleRowClick = (row) => {
  console.log('Row clicked:', row)
}

// Page size change
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadData()
}

// Current page change
const handleCurrentChange = (page) => {
  pagination.page = page
  loadData()
}

// Initialize
onMounted(() => {
  loadData()
  // 加载客户下拉数据
  http.get('api/WMS/GetAllCustomerInformation').then(res => {
    if (res && res.success && Array.isArray(res.data)) {
      customerOptions.value = res.data.map(x => ({ value: x.id, label: x.customerInformationName }))
    }
  })
})

// Helpers: 编码年月与序列
function getYearMonth() {
  const d = new Date()
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  return `${y}${m}`
}
function getNextSeq(ym) {
  const key = `srk_seq_${ym}`
  const last = parseInt(localStorage.getItem(key) || '0', 10)
  return isNaN(last) ? 1 : last + 1
}
</script>

<style lang="less" scoped>
.warehousings-container {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;

    .search-form {
      margin-bottom: -18px;
    }
  }

  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title {
        font-size: 16px;
        font-weight: bold;
      }
    }
.product-toolbar { margin-bottom: 10px; }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
  /* 调小表格行高 */
  :deep(.el-table__row) { height: 36px; }
  :deep(.el-table .cell) { line-height: 36px; padding: 4px 8px; }
}
</style>

